package top.fzqblog.firstapp;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.nfc.Tag;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.EventLogTags;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.FutureTarget;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.jakewharton.rxbinding.view.RxView;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import top.fzqblog.app.FirstApplication;
import top.fzqblog.util.FileUtils;
import top.fzqblog.util.StatusBarUtil;
import uk.co.senab.photoview.PhotoView;

/**
 * Created by 抽离 on 2017/9/30 0030.
 */

public class PhotoSee extends AppCompatActivity implements ViewPager.OnPageChangeListener{

    private static final String TAG = "tag";

    @BindView(R.id.photoRoot)
    public RelativeLayout photoRoot;

    @BindView(R.id.viewpager)
    public ViewPager viewPager;

    @BindView(R.id.viewpager_text)
    public TextView viewPagerText;

    @BindView(R.id.save_big_image)
    public TextView saveTV;

    //记录当前浏览图片的位置
    private int posi = 0;

    private List<String> imgList = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_see);
        ButterKnife.bind(this);
        StatusBarUtil.setColor(this, Color.BLACK);
        initData();
        initBinding();
    }

    private void initBinding() {
        viewPager.setOnPageChangeListener(this);
        RxView
                .clicks(saveTV)
                .throttleFirst(1, TimeUnit.SECONDS)
                .subscribe(
                        Void ->{
                            new DownImageTask().execute(imgList.get(posi));
                        }
                );
    }

    class DownImageTask extends AsyncTask<String, Integer, Void> {

        @Override
        protected Void doInBackground(String... params) {
            String imgUrl = params[0];
            File file = null;
            try {
                FutureTarget<File> future = Glide
                        .with(PhotoSee.this)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL);
                file = future.get();

                String filePath = file.getAbsolutePath();
                Log.i(TAG, "filepath:" + filePath);

                String destFileName = System.currentTimeMillis() + FileUtils.getImageFileExt(filePath);
                File destFile = new File(FileUtils.getDir(""), destFileName);

                FileUtils.copy(file, destFile);// 保存图片

                // 最后通知图库更新
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(new File(destFile.getPath()))));
            }
            catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Snackbar.make(photoRoot, "保存成功，图片所在文件夹:SD卡根路径/FirstApp", Snackbar.LENGTH_SHORT)
                    .setAction("好的", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            // Perform anything for the action selected
                        }
                    })
                    .show();
//            Toast.makeText(FirstApplication.getInstance(),
//                    "保存成功，图片所在文件夹:SD卡根路径/FirstApp",
//                    Toast.LENGTH_SHORT).show();
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            Log.i("tag", "进度："+ values[0]);
        }
    }

    private void initData() {
        Intent intent = getIntent();
        imgList = intent.getStringArrayListExtra("imgs");
        int position = intent.getIntExtra("position", 0);
        BigImgViewAdapter bigImgViewAdapter = new BigImgViewAdapter(this, imgList);
        viewPager.setAdapter(bigImgViewAdapter);
        viewPager.setCurrentItem(position);
        posi = position;
        setPagerText((position+1) + "/" + imgList.size());
    }

    private void setPagerText(String text){
        viewPagerText.setText(text);
    }
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        Log.i("tag", "当前页数" + position);
        setPagerText((position+1) + "/" + imgList.size());
        posi = position;
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
}

class BigImgViewAdapter extends PagerAdapter{

    private Context context;

    private List<String> imgs;

    public BigImgViewAdapter(Context context, List<String> imgs) {
        this.context = context;
        this.imgs = imgs;
    }

    @Override
    public int getCount() {
        if(imgs == null){
            return 0;
        }
        return imgs.size();
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
        return view == object;
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Log.i("tag", "加载第" + position + "张图片");
        View bigImgView = LayoutInflater.from(context).inflate(R.layout.big_image_layout, container, false);
        ProgressBar progressBar = bigImgView.findViewById(R.id.loading);
        PhotoView photoView = bigImgView.findViewById(R.id.photoView);
        Glide.with(context)
                .load(imgs.get(position))
                .crossFade(700)
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target, boolean isFirstResource) {
                        Toast.makeText(FirstApplication.getInstance(), "资源加载异常", Toast.LENGTH_SHORT).show();
                        progressBar.setVisibility(View.GONE);
                        return false;
                    }

                    //这个用于监听图片是否加载完成
                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                                                   Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        progressBar.setVisibility(View.GONE);
                        /**这里应该是加载成功后图片的高*/
                        int height = photoView.getHeight();
                        return false;
                    }
                }).into(photoView);
//        ImageView imageView = new ImageView(context);
//        Glide
//                .with(context)
//                .load(imgs.get(position))
//                .crossFade(700)
//                .into(imageView);

        container.addView(bigImgView);
        return bigImgView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        Log.i("tag", "移除第" + position + "张图片");
        container.removeView((View)object);
    }
}